<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="search-header">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索内容"
            clearable
            class="search-input"
            size="default"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="default" @click="handleSearch"
            >搜索</el-button
          >
          <el-button size="default" @click="handleReset">重置</el-button>
          <el-button type="success" size="default" @click="openAddUserDialog"
            >添加用户</el-button
          >
          <el-button
            type="danger"
            size="default"
            @click="deleteSelectedUsers"
            :disabled="selectedUsers.length === 0"
            >批量删除</el-button
          >
          <el-button
            type="info"
            size="default"
            @click="exportToCSV"
            >导出CSV</el-button
          >
        </div>
      </template>
      <el-table
        :data="filteredUsers"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        ref="userTable"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          align="center"
          label="用户名"
          min-width="150"
        />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column
          align="center"
          prop="gender"
          label="性别"
          min-width="60"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.gender == 1" type="success">男</el-tag>
            <el-tag v-else type="danger">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="phone"
          label="手机号"
          min-width="120"
        />
        <el-table-column
          align="center"
          prop="email"
          label="邮箱"
          min-width="150"
        />
        <el-table-column
          prop="avatar"
          label="头像"
          align="center"
          min-width="80"
        >
          <template #default="scope">
            <el-avatar
              :src="scope.row.avatar"
              alt="头像"
              style="width: 50px; height: 50px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="200">
          <template #default="scope">
            <el-button
              text
              type="primary"
              size="default"
              @click="openEditUserDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              text
              type="danger"
              size="default"
              @click="delUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :pager-count="9"
          layout="prev, pager, next"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户弹框 -->
    <el-dialog
      :title="dialogTitle"
      align-center
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="currentUser"
        :rules="rules"
        ref="userForm"
        label-width="80px"
        class="dialog-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="currentUser.username"
            placeholder="请输入用户名"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '添加用户'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="currentUser.password"
            placeholder="请输入密码"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="currentUser.nickname"
            placeholder="请输入昵称"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="currentUser.gender"
            placeholder="请选择性别"
            class="dialog-input"
          >
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="currentUser.phone"
            placeholder="请输入手机号"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="currentUser.email"
            placeholder="请输入邮箱"
            class="dialog-input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue"; // 引入搜索图标
import { saveAs } from "file-saver"; // 引入file-saver库用于保存文件

import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
  deleteUsers,
} from "@/request/request";

const searchQuery = ref("");
const users = ref([]);

const selectedUsers = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("添加用户");
const currentUser = ref({
  username: "",
  password: "",
  nickname: "",
  gender: "",
  phone: "",
  email: "",
  avatar: "",
});

const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 0 },
];

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  gender: [{ required: false, message: "请选择性别", trigger: "change" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱",
      trigger: "blur",
    },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 添加分页相关的响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

onMounted(() => {
  getUsers();
});

// 获取用户列表
const getUsers = async () => {
  try {
    const res = await getUserList(currentPage.value, pageSize.value);
    users.value = res.data.records;
    total.value = res.data.total; // 设置总数据量
  } catch (error) {
    console.error("获取用户列表失败", error);
  }
};

const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置页码到第一页
};

const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return users.value; // 当搜索框为空时，直接返回原始数据
  }
  return users.value.filter((user) => {
    return (
      (user.username &&
        user.username
          .toLowerCase()
          .includes(searchQuery.value.toLowerCase())) ||
      (user.nickname &&
        user.nickname
          .toLowerCase()
          .includes(searchQuery.value.toLowerCase())) ||
      (user.phone && user.phone.includes(searchQuery.value)) ||
      (user.email &&
        user.email.toLowerCase().includes(searchQuery.value.toLowerCase()))
    );
  });
});

const handleReset = () => {
  searchQuery.value = "";
  currentPage.value = 1; // 重置时将页码重置到第一页
  getUsers(); // 重新获取用户列表
};

const openAddUserDialog = () => {
  dialogTitle.value = "添加用户";
  currentUser.value = { username: "", email: "", role: "", status: "" };
  dialogVisible.value = true;
  // 重置表单校验
  if (userForm.value) {
    userForm.value.resetFields();
  }
};

const openEditUserDialog = (user) => {
  dialogTitle.value = "编辑用户";
  currentUser.value = { ...user };
  dialogVisible.value = true;
  // 重置表单校验
  if (userForm.value) {
    userForm.value.resetFields();
  }
};

const userForm = ref(null);
const handleSaveUser = () => {
  userForm.value.validate(async (valid) => {
    if (valid) {
      if (dialogTitle.value == "添加用户") {
        appendUser();
      } else {
        editUser();
      }
    }
  });
};

const appendUser = async () => {
  // 添加用户逻辑
  const res = await addUser(currentUser.value);
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getUsers();
  } else {
    ElMessage.error(res.msg);
  }
};

const editUser = async () => {
  // 编辑用户逻辑
  const res = await updateUser(currentUser.value.id, currentUser.value);
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getUsers();
  } else {
    ElMessage.error(res.msg);
  }
};

const delUser = async (user) => {
  // 删除用户逻辑
  ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteUser(user.id);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getUsers();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const deleteSelectedUsers = async () => {
  // 批量删除用户逻辑
  const ids = selectedUsers.value.map((user) => user.id);
  console.log(ids);
  ElMessageBox.confirm("确定要删除这些用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteUsers(ids);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getUsers();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (val) => {
  selectedUsers.value = val;
};

// 分页事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getUsers();
};

// 导出CSV功能
const exportToCSV = () => {
  const array = [
    ["序号", "用户名", "昵称", "性别", "手机号", "邮箱"],
    ...users.value.map((user, index) => [
      index + 1,
      user.username,
      user.nickname,
      user.gender === 1 ? "男" : "女",
      user.phone,
      user.email,
    ]),
  ];

  const csvContent = array.map((e) => e.join(",")).join("\n");

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  saveAs(blob, "user_list.csv");
};
</script>

<style scoped>
.user-list-container {
  background-color: #fff; /* 设置背景为奶白色 */
}

.search-header {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #fff; /* 设置背景为奶白色 */
}

.search-input {
  width: 200px;
}

.dialog-form {
  text-align: center;
  background-color: #ffffff; /* 设置背景为奶白色 */
}

.dialog-input {
  width: 100%;
  margin: 0 auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  background-color: #fff; /* 设置背景为奶白色 */
}

</style>
